import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20*1000,
})

export interface ServiceResponse<T> {
  code: number
  msg: string
  data: T
}
export const request = <T>(url:string,method:Method='GET',submitObject?:object)=>{
  return service.request<T,ServiceResponse<T>>({
    url:url,
    method:method,
    [method.toUpperCase()==='GET'?'params':'data']:submitObject
  })
}

service.interceptors.request.use(
  config => {
    const store = useUserStore()
    if(store.token){
      config.headers.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if(error.response){
      ElMessage.error(error.response.data.msg)
      if(error.response.status===401){
        router.push('/login')
        const store = useUserStore()
        store.removeToken()
        ElMessage.warning('登录已过期，请重新登录')
      }
    }else{
      ElMessage.error('网络错误，请稍后再试')
    }
    return Promise.reject(error)
  },
)

export default service
